/**
 * create by young (young2f@outlook.com) on 2020/11/4
 */

'use strict';
import React, {Component} from 'react';
import ProductionElement from '../ProductionElement';
import notify from '../NotificationExtra';
// import QRCode from 'qrcode.react';
import {Alert, Input, Popover, Select, Switch, Tag, Tooltip} from 'antd';
import moment from 'moment';
import DescriptionGroup from '../DescriptionGroup';

import styles from '../../routes/index.less';

const uuid = require('uuid');
const _ = require('lodash');
const _theme = require('../../theme');
const crypto = require('crypto');
const {TextArea} = Input;
const {Option} = Select;

export default class ComponentBase extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.loginInfo = wStore.getStore('loginInfo');
  }

// "13%", "9%", "6%", "3%", "1%", "0%"
  getTax(amount, taxRate = '0%') {
    switch (taxRate) {
      case '0%':
        return amount;
      case '13%':
        return amount / 1.13 * 0.13;
      case '9%':
        return amount / 1.09 * 0.09;
      case '6%':
        return amount / 1.06 * 0.06;
      case '3%':
        return amount / 1.03 * 0.03;
      case '1%':
        return amount / 1.01 * 0.01;
    }
  }

  getBase64(file) {
    console.log('file', file);
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  getOpt = (label, list) => {
    return list.map(opt => (<Option key={opt.code} value={opt.name} label={label}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {label === 'materials' ? opt.name + " " + opt.subcategory + " " + opt.spec : opt.name}
      </Option>
    ));
  };

  getCustomerOpt(customers) {
    return customers.map(opt => (<Option key={opt.code} value={opt.name}>
        {opt.name}
      </Option>
    ));
  }

  getDivision = (divisionDict) => {
    const temp = [];
    _.map(divisionDict, item => {
      const {name} = item;
      temp.push(<Option value={name}>{name}</Option>);
    });
    return temp;
  };
  getAccount = (accounts) => {
    const temp = [];
    _.map(accounts, item => {
      const {accountName, openingBank, account, code} = item;
      const name = accountName + " " + openingBank + " " + account;
      temp.push(<Option key={code} value={name}>{name}</Option>);
    });
    return temp;
  };
  getSelectOption = (list) => {
    let map = list ? list.map(item => {
      return (
        <Option value={item}>{item}</Option>
      );
    }) : null;
    return map;
  };

  // getOption = (list) => {
  //   let map = list ? list.map(item => {
  //     const {label, value} = item;
  //     return (
  //       <Option value={value}>{label}</Option>
  //     );
  //   }) : null;
  //   return map;
  // };

  getLoading = () => {
    return (<Alert
      message="数据加载中"
      type="info"
    />);

  };

  isJsonArray(body) {
    const obj = body ? Object.prototype.toString.call(body) : '';
    return obj === '[object Array]';
  }

  getThemeProp(str) {
    return _theme[str];
  }

  getPageTitle() {
    const {tenant} = this.getLoginInfo();
    return tenant && tenant.tenantShortName ? tenant.tenantShortName : '请登录';
  }

  getTenantName() {
    const {tenant} = this.getLoginInfo();

    return tenant && tenant.tenantName ? tenant.tenantName : '请登录';
  }

  getCryptoPassword(password) {
    try {
      const hash = crypto.createHash('sha256');// sha256或者md5
      hash.update(password);
      return hash.digest('hex');
    } catch (e) {
      console.error(e);
      return password;
    }
  }

  getModelStr(table) {
    return table.toLowerCase()
      .replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
  }

  editMenuData = (menu) => {
    menu.map(item => {
      const {path, children} = item;
      item.key = path;
      item.value = path;
      children && children.length && this.editMenuData(children);
    });
  };

  getLoginUser() {
    const str = this.loginInfo ? this.loginInfo.username : undefined;
    return str;
  }

  getLoginInfo() {
    return this.loginInfo ? this.loginInfo : {};
  }

  getLoginUsername() {
    const str = this.loginInfo ? this.loginInfo.nickname : undefined;
    return str;
  }

  getTenantCode() {
    const str = this.loginInfo ? this.loginInfo.tenantCode : undefined;
    return str;
  }

  getSearchStart1Months() {
    return moment().startOf('day').subtract(1, 'months');
  }

  getSearchStart1Year() {
    return moment().startOf('day').subtract(1, 'years');
  }

  getDefaultSearchEndDate() {
    return moment().endOf('day');
  }

  getDefaultSearchStart7Date() {
    return moment().startOf('day').subtract(7, 'days');
  }

  getDefaultSearchStart1Date() {
    return moment().startOf('day').subtract(1, 'days');
  }

  getDefaultSearchStart12Months() {
    return moment().startOf('month').subtract(12, 'months');
  }

  getDefaultSearchEndMonth() {
    return moment().endOf('month');
  }

  getTreeSubTitle(treeNode) {
    if (!treeNode) return '';
    const {fatherName, fatherTitle, treeId} = treeNode;
    const {name, title} = treeNode;
    let _father = fatherName ? fatherName : fatherTitle || '';
    let _name = name ? name : title.name;
    let father = _father ? `/ ${_father}` : '';
    return `${father} / ${_name}`;
    // return `${father} / ${_name} / ${treeId}`;
  }

  getProductionElement(code, name, unit) {
    return (
      <ProductionElement unit={unit} code={code} name={name}></ProductionElement>
    );
  }

  getColumns(dynamicLabels, title, width) {
    const list = _.clone(dynamicLabels);
    _.remove(list, function (item) {
      return (item.key === 'code' || item.key === 'name' || item.key === 'unit');
    });
    const temp = [{
      title: title, dataIndex: 'code', key: 'code', width, ellipsis: true,
      render: (value, record) => {
        return this.getProductionElement(record['code'], record['name'], record['unit']);
      }
    }];

    list && list.length && list.map(item => {
      const {label, key, enableArea} = item;
      const _key = `labels.${key}`;
      _.includes(enableArea, 'table') && temp.push({title: label, dataIndex: _key, key: _key, ellipsis: true});
    });
    return temp;
  }

  requestCode = (prefix, result) => {
    this.props.dispatch({
      type: 'global/getCode',
      payload: {prefix}
    }).then(res => {
      const {code} = res;
      result(code);
    });
  };


  requestReturn = (res) => {
    if (!res) {
      notify({message: '操作失败，无服务！', type: 'error'});
    } else {
      const {status, message} = res;
      if (status !== 'ok') {
        notify({message, type: 'error'});
      } else {
        notify({message: '操作成功', type: 'info'});
      }
    }
  };


  getUUID(size = 8) {
    const id = uuid.v4();
    id.toString()
      .replace(/\-/g, '');
    const temp = id.slice(0, size)
      .toUpperCase();
    return temp;
  }


}
